package com.xry.test1.service.impl;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xry.test1.dao.GasRepository;
import com.xry.test1.dao.LightRepository;
import com.xry.test1.model.AirData;
import com.xry.test1.model.LightData;
import com.xry.test1.service.MQTTSubscriber.MQTTSubscribe;
import com.xry.test1.service.MQTTSubscriber.MqttMessageHandler;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import jakarta.annotation.PostConstruct;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Objects;

@Service
public class LightService implements MqttMessageHandler {
    //数据库

    public String updatedState= "000";

    @Autowired
    private SimpMessagingTemplate messagingTemplate; // WebSocket 消息推送

    private static final Logger LOGGER = LoggerFactory.getLogger(LightService.class);
    private static final String LIGHT_STATE_TOPIC = "bedroom"; // 订阅灯状态的主题
    //private static final String LIGHT_CMD_TOPIC = "bedroom_cmd"; // 发送灯控制指令的主题


    @Autowired
    private LightRepository lightRepository;

    @Autowired
    private MQTTSubscribe mqttSubscribe;

    //private String currentLightState = "000"; // 默认初始灯状态

    private LightData lastLightData;

    /**
     * 在服务启动时订阅 bedroom_state 主题，监听灯的状态变化
     */
    @PostConstruct
    public void init() {
        // 订阅 bedroom_state 主题，并设置 LightService 作为回调处理器
        mqttSubscribe.subscribeToTopic(LIGHT_STATE_TOPIC, this);
        LOGGER.info("✅ LightService 已订阅主题：{}", LIGHT_STATE_TOPIC);
    }

    /**
     * 处理收到的 MQTT 消息，更新灯的状态
     */
    @Override
    public void handleIncomingMessage(String topic, MqttMessage message) {
        if (!LIGHT_STATE_TOPIC.equals(topic)) {
            return; // 过滤掉非 bedroom_state 的消息
        }

        System.out.println(message);

        try {
            String payload = new String(message.getPayload());
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(payload);

            Integer light1 = jsonNode.get("l0").asInt();
            Integer light2 = jsonNode.get("l1").asInt();
            Integer light3 = jsonNode.get("l2").asInt();

//            System.out.println("light1:" + light1);
//            System.out.println("light2:" + light2);
//            System.out.println("light3:" + light3);

            LightData lightData = new LightData();
            lightData.setLight1(light1);
            lightData.setLight2(light2);
            lightData.setLight3(light3);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            lightData.setDate(LocalDateTime.now().format(formatter));

            lastLightData = lightData;

            //mysql
//            lightRepository.save(lightData);

            // 推送数据到 WebSocket

        } catch (Exception e) {
            LOGGER.error(" 解析灯状态消息失败", e);
        }
    }

    /**
     * 获取当前灯的状态，供前端调用
     */
    public LightData getLightState() {
//        LOGGER.info("返回当前灯状态: {}", currentLightState);
//        return currentLightState;
        lastLightData.setDate(LocalDateTime.now().toString());
        try{
            messagingTemplate.convertAndSend("/topic/lightData", lastLightData);
            System.out.println("灯 推送 WebSocket 数据：" + lastLightData.getLight1()+lastLightData.getLight2()+lastLightData.getLight3());
            return lastLightData;
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

    public boolean controlLight(int lightNumber, String turnOn) {
        System.out.println("灯编号: " + lightNumber);
        System.out.println("操作: " + turnOn);

        // 检查灯编号是否有效
        if (lightNumber < 1 || lightNumber > 3) {
            LOGGER.warn("⚠️ 无效的灯编号: {}", lightNumber);
            return false;
        }

        try {
            // 保留原有的灯状态（假设当前状态为 "lastLightData"）
            char[] newState = new char[3];
            newState[0] = lastLightData.getLight1() == 1 ? '1' : '0';
            newState[1] = lastLightData.getLight2() == 1 ? '1' : '0';
            newState[2] = lastLightData.getLight3() == 1 ? '1' : '0';

            // 更新指定的灯的状态
            newState[lightNumber - 1] = turnOn.charAt(0);  // 更新目标灯的状态

            //updatedState = Arrays.toString(newState); // 更新后的灯状态字符串
//            StringBuilder updatedState = new StringBuilder();
//            for (char state : newState) {
//                updatedState.append(state);
//            }



            // 发送新的灯状态到 MQTT
            //mqttSubscribe.sendMQTTMessage(LIGHT_CMD_TOPIC, updatedState, 2);
            //LOGGER.info("✅ 发送灯控制指令: {}", updatedState);

            // 更新 lastLightData，以便下一次调用 getLightState 时返回正确的状态
            if (lightNumber == 1) {
                lastLightData.setLight1(turnOn.charAt(0) == '1' ? 1 : 0);
            } else if (lightNumber == 2) {
                lastLightData.setLight2(turnOn.charAt(0) == '1' ? 1 : 0);
            } else {
                lastLightData.setLight3(turnOn.charAt(0) == '1' ? 1 : 0);
            }

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            lastLightData.setDate(LocalDateTime.now().format(formatter));

            String updatedState = String.valueOf(lastLightData.getLight1()) +
                    lastLightData.getLight2() +
                    lastLightData.getLight3();

            this.updatedState = updatedState;
            System.out.println("——————————————控制_____________"+updatedState);

            //mysql
            lightRepository.save(lastLightData);

            return true;

        } catch (Exception e) {
            LOGGER.error("❌ 发送灯控制指令失败", e);
            return false;
        }
    }

    public String getLastLight() {
        //System.out.println("getLastLight::::"+updatedState);

        return updatedState;
    }
}
